﻿#include "PointTrackWindow.h"
#include "utils/Color/ColorGen.h"

#include <QPainter>
#include <QTimer>
#include <QWindow>
#include <QDebug>

PointTrackWindow::PointTrackWindow(QWidget *parent)
    : QWidget(parent)
{
    // 无边框，置顶，透明背景
    setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::Tool);

    // 启用透明背景
    setAttribute(Qt::WA_TranslucentBackground);

    // 鼠标穿透（让事件穿透到下面窗口）
    setAttribute(Qt::WA_TransparentForMouseEvents);


    m_canvas = QPixmap(size());
}

void PointTrackWindow::setOpacity(uint8_t opacity)
{
    // 0 不透明，100 全透明，转换成 alpha (0-255)
    opacity = opacity > 100 ? 100 : opacity;
    m_opacity = 255 - (255 * opacity / 100);
    update();
}

void PointTrackWindow::clear()
{
    m_lastPoints.clear();
    if (!m_canvas.isNull()) {
        m_canvas.fill(Qt::transparent); // 清成透明背景
        update(); // 触发重绘
    }
}

QColor PointTrackWindow::colorForIndex(int index) const
{
    return ColorGen::getColor(index);
}

void PointTrackWindow::setPoints(const QList<TouchPoint> &points)
{
    QPainter p(&m_canvas);
    p.setRenderHint(QPainter::Antialiasing, true);

    for (int i = 0; i < points.size(); ++i)
    {
        const TouchPoint &tp = points[i];
        if (!tp.isValid())
            continue;

        QColor color = ColorGen::getColor(i);
        QPen pen(color, 2);
        p.setPen(pen);
        p.setBrush(color);

        p.drawEllipse(QPointF(tp.x(), tp.y()), 5, 5);

        if (i < m_lastPoints.size())
        {
            const TouchPoint &lastTp = m_lastPoints[i];
            if (lastTp.isValid())
            {
                p.drawLine(QPointF(lastTp.x(), lastTp.y()), QPointF(tp.x(), tp.y()));
            }
        }
    }

    m_lastPoints = points;
    update();
}

void PointTrackWindow::paintEvent(QPaintEvent * /*event*/)
{
    QPainter p(this);
    p.setRenderHint(QPainter::Antialiasing, true);

    // 绘制半透明背景
    p.fillRect(rect(), QColor(0, 0, 0, m_opacity));

    p.drawPixmap(0, 0, m_canvas);
}

void PointTrackWindow::resizeEvent(QResizeEvent *event)
{
    Q_UNUSED(event);
    m_canvas = QPixmap(size());
    m_canvas.fill(Qt::transparent);
}
